using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace udpbroadcast
{
    internal class Program
    {
        static IPAddress[] GetLocalIp()
        {
            IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress[] addr = ipEntry.AddressList;
            var result = Array.FindAll(addr, ip => ip.AddressFamily == AddressFamily.InterNetwork);
            return result.ToArray();
        }
        static IPAddress[] GetLocalIp2()
        {
            IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
            var result = from s in ipEntry.AddressList
                         where s.AddressFamily == AddressFamily.InterNetwork
                         select s;
            return result.ToArray();
        }
        static List<UdpClient> CreateUdp(IPAddress[] Ip4)
        {
            List<UdpClient> UDPsenders = new List<UdpClient>();
            for (int i = 0; i < Ip4.Length; i ++)
            {
                // IPAddress.Parse("192.168.0.222")
                // IPAddress.Any
                UDPsenders.Add(new UdpClient(new IPEndPoint(Ip4[i], 0)));
            }
            return UDPsenders;
        }
        static UdpClient[] CreateUdp2(IPAddress[] Ip4)
        {
            UdpClient[] UDPsenders = new UdpClient[Ip4.Length];
            for (int i = 0; i < Ip4.Length; i++)
            {
                UDPsenders[i] = new UdpClient(new IPEndPoint(Ip4[i], 0));
            }
            return UDPsenders;
        }
        static void Main(string[] args)
        {
            var local_addr = GetLocalIp();
            foreach (var ip in local_addr)
            {
                Console.WriteLine("Local IP Address: {0} ", ip.ToString());
            }
            var UDPsenders = CreateUdp2(local_addr);
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Broadcast, 22222);

            Thread receThread = new Thread(new ThreadStart(RecvThread));
            receThread.IsBackground = true;
            receThread.Start();

            int send_count = 0;
            while (true)
            {
                byte[] buf = Encoding.Default.GetBytes("This is UDP broadcast:" + send_count ++);
                foreach (var udpsender in UDPsenders)
                {
                    udpsender.Send(buf, buf.Length, endpoint);
                }
                Thread.Sleep(1000);
            }
        }
        static void RecvThread()
        {
            UdpClient UDPrece = new UdpClient(new IPEndPoint(IPAddress.Any, 55555));
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                byte[] buf = UDPrece.Receive(ref endpoint);
                string msg = Encoding.Default.GetString(buf);
                Console.WriteLine(msg);
            }
        }
    }
}
